package com.mybatis.plus.join.column;

import com.mybatis.plus.join.ColumnData;
import lombok.Data;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Data
public class SubtractColumn implements Column {
    private Column sourceColumn;
    private Column[] column;
    private String asName;


    public SubtractColumn(Column sourceColumn, Column... column) {
        Assert.notNull(sourceColumn, "sourceColumn can not be null");
        this.sourceColumn = sourceColumn;
        this.column = column;
    }

    public SubtractColumn(String asName, Column sourceColumn, Column... column) {
        Assert.notNull(sourceColumn, "sourceColumn can not be null");
        this.sourceColumn = sourceColumn;
        this.column = column;
        this.asName = asName;
    }

    @Override
    public String selectColumn() {
        if (asName == null || "".equals(asName.trim())) {
            return getSql();
        }
        return "(" + getSql() + ") AS " + asName;
    }

    private String getSql() {
        List<Column> list = new ArrayList<>();
        list.add(sourceColumn);
        list.addAll(Arrays.asList(column));
        return list.stream().map(Column::selectColumn)
                .collect(Collectors.joining(" - "));
    }

    @Override
    public void fillData(ColumnData columnData) {
        for (Column c : column) {
            c.fillData(columnData);
        }
    }
}